package com.stone.framework.batch.support;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.configuration.DuplicateJobException;
import org.springframework.batch.core.configuration.JobFactory;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.Assert;

import com.stone.framework.core.exception.BusinessException;

public class JdbcJobRegistry implements JobRegistry, InitializingBean {

    @Autowired
    private JobRegistry mapJobRegistry;

    private String serviceName;

    private DataSource dataSource;

    private NamedParameterJdbcOperations jdbcTemplate;

    @Override
    public void register(JobFactory jobFactory) throws DuplicateJobException {
        mapJobRegistry.register(jobFactory);

        String name = jobFactory.getJobName();
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("jobName", name);
        paramMap.put("serviceName", this.serviceName);

        Integer count = jdbcTemplate.queryForObject("SELECT COUNT(1) FROM ST_JOB_REGISTER WHERE JOB_NAME = :jobName",
            paramMap, Integer.class);
        if (count == 0) {
            jdbcTemplate.update("INSERT INTO ST_JOB_REGISTER(JOB_NAME, SERVICE_NAME) VALUES (:jobName, :serviceName)",
                paramMap);
        } else {
            jdbcTemplate.update("UPDATE ST_JOB_REGISTER SET SERVICE_NAME = :serviceName WHERE JOB_NAME = :jobName",
                paramMap);
        }
    }

    @Override
    public Job getJob(String name) throws NoSuchJobException {
        throw new BusinessException("不支持该方法");
    }

    @Override
    public Collection<String> getJobNames() {
        throw new BusinessException("不支持该方法");
    }

    @Override
    public void unregister(String jobName) {
        mapJobRegistry.unregister(jobName);
    }

    @Override
    public void afterPropertiesSet() throws IllegalArgumentException {
        Assert.notNull(this.dataSource, "dataSource must not be null");
        this.jdbcTemplate = new NamedParameterJdbcTemplate(this.dataSource);
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

}
